package com.fashiontextile.user.service.impl;

import com.fashiontextile.admin.entity.Dict;
import com.fashiontextile.user.entity.Image;
import com.fashiontextile.common.utils.AliyunOSSUtils;
import com.fashiontextile.common.utils.IdUtils;
import com.fashiontextile.user.mapper.ImageMapper;
import com.fashiontextile.user.service.ImageService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * @author brooke_zb
 */
@Service
@AllArgsConstructor
public class ImageServiceImpl implements ImageService {
    private IdUtils idUtils;
    private AliyunOSSUtils ossUtils;
    private ImageMapper imageMapper;

    @Override
    public Image getImageById(Long iid) {
        return imageMapper.selectImageById(iid);
    }

    @Override
    public List<Image> getImageByPointTo(Long imageTypeId, Long pointTo) {
        return imageMapper.selectImage(imageTypeId, pointTo);
    }

    @Override
    public Image uploadImage(Long diid, MultipartFile picture) throws Exception {
        long iid = idUtils.nextId();
        String fileExtension = Objects.requireNonNull(picture.getOriginalFilename()).substring(picture.getOriginalFilename().lastIndexOf("."));
        String pictureUrl = (String) ossUtils.uploadMultipart(picture, iid + fileExtension).getData();

        Dict dict = new Dict();
        dict.setDid(diid);

        Image image = new Image();
        image.setIid(iid);
        image.setImageType(dict);
        image.setLink(pictureUrl);
        return image;
    }

    @Override
    public boolean uploadImageLink(List<Image> images) {
        return imageMapper.insertImages(images) > 0;
    }

    @Override
    public boolean deleteImageByPointTo(Long pointTo, Long diid) {
        return imageMapper.deleteImageByPointTo(diid, pointTo) > 0;
    }

    @Override
    public boolean deleteImageById(Long id) {
        return imageMapper.deleteImage(id) > 0;
    }
}
